﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using DevMaker.SIC.Model;
using log4net;


namespace DevMaker.SIC.Dao {
    public class ReposicionDao {
        private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public Reposicion Crear(Turno turno, Reposicion reposicion, SqlTransaction transaction) {
            const string storeName = "sp_reposiciones_c";
            try {
                var command = new SqlCommand(storeName, transaction.Connection) { Transaction = transaction, CommandType = CommandType.StoredProcedure };
                command.Parameters.AddWithValue("@id_sucursal", turno.Sucursal.Id);
                command.Parameters.AddWithValue("@cod_sucursal", turno.Sucursal.Codigo);
                command.Parameters.AddWithValue("@id_turno", turno.Id);
                command.Parameters.AddWithValue("@id_supervisor", reposicion.Supervisor.Id);
                command.Parameters.AddWithValue("@fecha", reposicion.Fecha);
                command.Parameters.AddWithValue("@es_inicio", reposicion.EsInicio);

                var outParam = command.Parameters.Add("@id", SqlDbType.BigInt);
                outParam.Direction = ParameterDirection.Output;
                command.ExecuteScalar();
                reposicion.Id = Convert.ToInt32(outParam.Value);
                var reposicionDetalleDao = new ReposicionDetalleDao();
                foreach (var reposicionDetalle in reposicion.Detalle)
                    reposicionDetalleDao.Crear(turno, reposicion, reposicionDetalle, transaction);
            } catch (Exception ex) {
                Log.Error(ex);
                throw ex;
            }
            return reposicion;
        }

        public Reposicion Crear(Turno turno, Reposicion reposicion) {
            var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SIC_Connection"].ToString());
            SqlTransaction trans = null;
            try {
                conn.Open();
                trans = conn.BeginTransaction();
                reposicion = Crear(turno, reposicion, trans);
                trans.Commit();
            } catch (Exception ex) {
                Log.Error(ex);
                reposicion.Id = 0;
                if (trans != null)
                    trans.Rollback();
                throw;
            } finally {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
            }
            return reposicion;
        }

        public List<Reposicion> ObtienePorTurno(Turno turno) {
            var reposiciones = new List<Reposicion>();
            var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SIC_Connection"].ToString());
            try {
                conn.Open();
                var command = new SqlCommand("sp_reposiciones_por_id_turno_l", conn) { CommandType = CommandType.StoredProcedure };
                command.Parameters.AddWithValue("@id", turno.Id);
                var reader = command.ExecuteReader();
                var r = new Reposicion();
                while (reader.Read()) {
                    if (r.Id != Convert.ToInt32(reader["reposicion_id"])) {
                        r = new Reposicion();
                        r.ReadFromDataReader(reader);
                        reposiciones.Add(r);
                        var reposicionDetalle = new ReposicionDetalle();
                        reposicionDetalle.ReadFromDataReader(reader);
                        r.Detalle.Add(reposicionDetalle);
                    } else {
                        var reposicionDetalle = new ReposicionDetalle();
                        reposicionDetalle.ReadFromDataReader(reader);
                        r.Detalle.Add(reposicionDetalle);
                    }
                }
            } catch (Exception ex) {
                Log.Error(ex);
                throw;
            } finally {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
            }
            return reposiciones;
        }
    }
}
